package com.andy.qhb.controller.game;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.andy.qhb.base.HttpClientUtil;
import com.andy.qhb.base.RespVO;
import com.andy.qhb.controller.GameController;
import com.andy.qhb.dao.DaoUtils;
import com.andy.qhb.dao.vo.Where;
import com.andy.qhb.entity.UsrFriends;
import com.andy.qhb.entity.UsrGameInfo;
import com.andy.qhb.entity.UsrUser;
import com.andy.qhb.exception.GoSeviceException;
import com.andy.qhb.game.GameConf;
import com.andy.qhb.game.GameUser;
import com.andy.qhb.game.GameUtils;
import com.andy.qhb.game.Global;
import com.andy.qhb.game.GlobalHttp;
import com.andy.qhb.game.Room;
import com.andy.qhb.utils.GoConstant;
import com.andy.qhb.utils.JsonUtils;

@Controller
@RequestMapping(value="game/api")
public class Api100Controller extends GameController{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	static String APPID = "wx8bf4160ad4f30f40";
	static String SECRET = "f89ce7254a05f8f32edd86d33ff39e85";
	
	static String redirect_uri = "http%3A%2F%2Fwww.60397n.cn/game/api/wx100"; // 微信重定向页面地址&state=STATE#wechat_redirect
	
	static String wx_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APPID+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo"; 
	
	@ResponseBody
	@RequestMapping(value="100")
	public RespVO action(HttpSession session,String data) throws Exception{
		Map<String, Object> reqData = JsonUtils.json2Map(data);
		String userName = MapUtils.getString(reqData, "userName");
		Long puid = MapUtils.getLong(reqData, "puid");
		
		GameUser gameUser = getUserSafe(session);
		if(gameUser != null) {
			UsrUser user = gameUser.getUser();
			if(puid != null && user.getPuid() != null && user.getPuid() == 0) {
				// 没有上线的设置为上线
				user.setPuid(puid);
				DaoUtils.update(user);
			}
			
			Map<String, Object> result = gameUser.getUserInfo();
			result.put("room", Global.getNorRooms());
			return RespVO.createSuccessJsonResonse(result);
		}
		
		gameUser = login(userName, null, null, null,puid);
		if(gameUser == null) {
			return RespVO.createErrorJsonResonse("用户不存在");
		}
		
		session.setAttribute(GoConstant.USER_SESSION_KEY, gameUser.getId());
		
		Map<String, Object> result = gameUser.getUserInfo();
		result.put("room", Global.getNorRooms());
		return RespVO.createSuccessJsonResonse(result);
		
	}

	private GameUser login(String userName, String openId, String nickname, String headimgurl,Long puid) {
		
		boolean isFromWx = StringUtils.isNotBlank(openId);
		
		GameUser gameUser = null;
		UsrUser user = null;
		boolean isNew = false;
		if(isFromWx) {
			user = DaoUtils.getOne(UsrUser.class, Where.eq("user_Name", openId));
			isNew = user == null;
		}else {
			isNew = StringUtils.isBlank(userName);
		}
		
		if(isNew){
			// 注册
			user = new UsrUser();
			user.setUserName(isFromWx?openId:RandomStringUtils.randomAlphabetic(10));
			user.setNickName(isFromWx?nickname:GameUtils.genNickName());
			user.setPassword("123456");
			user.setRole(0);
			user.setPuid(puid);
			user.setLoginTime(System.currentTimeMillis()/1000);
			user.setIcon(isFromWx?headimgurl:String.valueOf(RandomUtils.nextInt(1, 60)));
			DaoUtils.insert(user);
			
			UsrGameInfo gameInfo = new UsrGameInfo();
			gameInfo.setUid(user.getId());
			gameInfo.addCoin(GameConf.getConfInt("init_coin"));
			gameInfo.setWinCount(0);
			gameInfo.setLoseCount(0);
			DaoUtils.insert(gameInfo);
			
			UsrFriends friends = new UsrFriends();
			friends.setUid(user.getId());
			DaoUtils.insert(friends);
			
			gameUser = new GameUser(user);
			gameUser.setGameInfo(gameInfo);
			gameUser.setFriends(friends);
			
			GlobalHttp.addUser(gameUser);
		}else{
			// 登录
			if(!isFromWx) {
				user = DaoUtils.getOne(UsrUser.class, Where.eq("user_Name", userName));
				if(user == null || user.getRole() > 0) {
					return null;
				}
			}
			gameUser = GlobalHttp.getUser(user.getId());
			if(gameUser == null){
				UsrGameInfo gameInfo = DaoUtils.getOne(UsrGameInfo.class, Where.eq("uid", user.getId()));
				UsrFriends friends = DaoUtils.getOne(UsrFriends.class, Where.eq("uid", user.getId()));
				gameUser = new GameUser(user);
				gameUser.setGameInfo(gameInfo);
				gameUser.setFriends(friends);
				
				GlobalHttp.addUser(gameUser);
			}else {
				user = gameUser.getUser();
				Room room = gameUser.getRoom();
				if(room != null) {
					room.removeUser(gameUser);
				}
			}
			
			if(puid != null && user.getPuid() != null && user.getPuid() == 0) {
				// 没有上线的设置为上线
				user.setPuid(puid);
			}
			if(isFromWx) {
				// 微信更新头像
				user.setIcon(headimgurl);
			}
			user.setLoginTime(System.currentTimeMillis()/1000);
			DaoUtils.update(user);
		}
		
		return gameUser;
	}
	
	@RequestMapping(value="wx100")
	public String wx100(HttpSession session,String code,String state) throws Exception{
		if(StringUtils.isBlank(code)) {
			throw new GoSeviceException("授权失败");
		}
		Long puid = 0L;
		if(StringUtils.isNotBlank(state)) {
			try {
				puid = Long.valueOf(state);
			} catch (Exception e) {
				logger.error(state,e);
			}
		}
		
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APPID+"&secret="+SECRET+"&code="+code+"&grant_type=authorization_code";
		String json = HttpClientUtil.post(url , null, null);
		if(json != null) {
			Map<String, Object> result = JsonUtils.json2Map(json);
			if(result.containsKey("errcode")) {
				logger.error("wx100 access_token error:"+json);
				throw new GoSeviceException((String)result.get("errmsg"));
			}else {
				url = "https://api.weixin.qq.com/sns/userinfo?access_token="+result.get("access_token")+"&openid="+result.get("openid")+"&lang=zh_CN";
				json = HttpClientUtil.post(url , null, null);
				if(json != null) {
					result = JsonUtils.json2Map(json);
					if(result.containsKey("errcode")) {
						logger.error("wx100 userinfo error:"+json);
						throw new GoSeviceException((String)result.get("errmsg"));
					}else {
						GameUser gameUser = login(null,MapUtils.getString(result, "openid"),MapUtils.getString(result, "nickname"),
								MapUtils.getString(result, "headimgurl"),puid);
						session.setAttribute(GoConstant.USER_SESSION_KEY, gameUser.getId());
						
						return "redirect:/";
					}
				}
			}
		}
		
		throw new GoSeviceException("授权失败");
	}

	
}